﻿using DatabaseCore;
using DatabaseCore.Dao;
using Export.SAP.Service;
using Newtonsoft.Json;
using OGA.NPI.ICSH.ServiceBase.Entities;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.SessionState;

namespace Export.Web.Ui2.service
{
    /// <summary>
    /// Summary description for api
    /// </summary>
    public class api : IHttpHandler, IReadOnlySessionState
    {
        private OrderDao orderProvider = null;
        private OrderDetailDao orderDetailsProvider = null;
        private ProdQueueDao queueProvider = null;
        private RoleDao roleProvider = null;
        private UserDao userProvider = null;
        private TransactionDao transectionDao = null;

        public void ProcessRequest(HttpContext context)
        {
            HttpRequest post = context.Request;
            string ADAuthen = context.User.Identity.Name;
            string ip = HttpContext.Current.Request.UserHostAddress;
            string Medthod = post["metdhodName"];
            context.Response.ContentType = "text/plain";
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string _username = HttpContext.Current.Session["Username"] == null ? "" : HttpContext.Current.Session["Username"].ToString();
            int _role = HttpContext.Current.Session["Role"] == null ? -1 : Convert.ToInt32(HttpContext.Current.Session["Role"]);

            if (!String.IsNullOrEmpty(Medthod))
            {

                switch (Medthod.Trim())
                {
                    #region Order Function
                    case "GetOrderAll":

                        orderProvider = orderProvider ?? new OrderDao();
                        var orderAll = orderProvider.Search(null, 0, null, null, null, null, null, _role);
                        string orderAllSerialized = serializer.Serialize(orderAll);
                        context.Response.Write(orderAllSerialized);
                        context.Response.End();
                        break;
                    case "GetOrderDetails":
                        string orderId = post["orderId"];
                        if (string.IsNullOrEmpty(orderId))
                        {
                            break;
                        }
                        else
                        {
                            orderDetailsProvider = orderDetailsProvider ?? new OrderDetailDao();
                            var orderDetails = orderDetailsProvider.SearchByOrderNo(orderId);
                            string orderDetailsSerialized = serializer.Serialize(orderDetails);
                            context.Response.Write(orderDetailsSerialized);
                            context.Response.End();
                            break;
                        }

                    case "UpdateDocument":
                        string documents = post["postData[documents]"];
                        string documentDetails = post["postData[documentDetails]"];
                        var d = JsonConvert.DeserializeObject<tbl_Order>(documents);
                        var details = JsonConvert.DeserializeObject<List<tbl_OrderDetail>>(documentDetails);
                        orderProvider = orderProvider ?? new OrderDao();
                        orderDetailsProvider = orderDetailsProvider ?? new OrderDetailDao();
                        orderProvider.Update(d);
                        orderDetailsProvider.Update(details, d.OrderNo, HttpContext.Current.User.Identity.Name);
                        break;

                    case "GetATP":
                        string prodIds = post["postData[prodIds]"];
                        var prodids = JsonConvert.DeserializeObject<string[]>(prodIds);
                        var productMovementHelper = new ProductMovement();

                        var products = new List<tbl_OrderDetail>();
                        foreach (var prodId in prodids)
                        {
                            products.Add(new tbl_OrderDetail() { MaterialNo = prodId });
                        }

                        DataSet result = productMovementHelper.testGetATP(products, true);
                        string productAtpSerialized = JsonConvert.SerializeObject(result);
                        context.Response.Write(productAtpSerialized);
                        context.Response.End();

                        break;

                    case "ApproveOrder":
                        string documentApprove = post["postData[documents]"];
                        string documentApproveDetails = post["postData[documentDetails]"];
                        var dApprove = JsonConvert.DeserializeObject<tbl_Order>(documentApprove);
                        var detailsApprove = JsonConvert.DeserializeObject<List<tbl_OrderDetail>>(documentApproveDetails);
                        orderProvider = orderProvider ?? new OrderDao();
                        orderProvider.UpdateOrderStatus(dApprove.OrderNo, 3, HttpContext.Current.Session["Username"].ToString());
                        
                        var productMovementApproveHelper = new ProductMovement();

                        DataSet resultApproveOrder = productMovementApproveHelper.testGetATP(detailsApprove, false);
                        List<tbl_Transaction> Ts = new List<tbl_Transaction>();

                        for (int i = 0; i < resultApproveOrder.Tables.Count; i++)
                        {
                            foreach (var detail in detailsApprove)
                            {
                                if (resultApproveOrder.Tables[i].TableName == detail.MaterialNo)
                                {
                                    detail.ATP = Convert.ToInt32(Convert.ToDouble(resultApproveOrder.Tables[i].Rows[0].Field<String>("ATPQty")));
                                    var t = new tbl_Transaction();
                                    t.OrderNo = detail.OrderNo;
                                    t.MaterialNo = detail.MaterialNo;
                                    t.Plant = detail.Plant;
                                    t.Qty = detail.TransferQty;

                                    Ts.Add(t);
                                }
                            }
                        }

                        //ResponseGoodsMovementEntity resultSapMoved = productMovementApproveHelper.productMove(Ts);
                        //Todo need to verify the success from sap before add to Quese
                        var addToQueseComplete = new List<ProdQueue>();
                        if (true)//resultSapMoved.Result)
                        {
                            //Prepare moved completed 
                            transectionDao = transectionDao ?? new TransactionDao();
                            List<tbl_Transaction> TsComplete = new List<tbl_Transaction>();
                            foreach (var item in Ts)
                            {
                                item.Qty = item.Qty * -1;
                                item.Result = "test";//resultSapMoved.MaterialDocumentNo;
                                item.IsMoveCompleted = true;
                                item.UpdateBy = "ATP";
                                item.UpdateDate = DateTime.Now;
                                TsComplete.Add(item);
                            }
                            //Add moved complete to transection
                            transectionDao.InsertCollection(TsComplete);

                            //Prepare the rest from atp to queue
                            foreach (var detail in detailsApprove)
                            {
                                if (detail.Qty - detail.TransferQty > 0)
                                {
                                    var q = new ProdQueue();
                                    q.ProductCode = detail.MaterialNo;
                                    q.PlantCode = detail.Plant;
                                    q.OrderNo = detail.OrderNo;
                                    q.Qty = detail.Qty - detail.TransferQty;
                                    q.Date = DateTime.Now;
                                    q.Rate = detail.Rate;
                                    q.ValidFrom = detail.ValidFrom;
                                    q.ValidTo = detail.ValidTo;
                                    q.IsActive = true;
                                    addToQueseComplete.Add(q);
                                }
                            }

                            queueProvider = queueProvider ?? new ProdQueueDao();
                            //add to queue
                            var insertQuestResult = queueProvider.InsertCollection(addToQueseComplete);

                            //update order details
                            orderDetailsProvider = orderDetailsProvider ?? new OrderDetailDao();
                            
                            foreach (var o in detailsApprove)
	                        {
                                orderDetailsProvider.UpdateReceivedQty(o.OrderNo,o.ItemNo, o.TransferQty, _username);
	                        }
                            
                        }

                        context.Response.Write("success");
                        context.Response.End();

                        break;
                    #endregion

                    #region Queue Funciton

                    case "GetQueueAll":

                        queueProvider = queueProvider ?? new ProdQueueDao();
                        var queues = queueProvider.GetAllQueues();
                        string queuesSerialized = serializer.Serialize(queues);
                        context.Response.Write(queuesSerialized);
                        context.Response.End();
                        break;

                    case "UpdateQueueStatus":
                        string queueId = post["postData[queueId]"];
                        string queueStatus = post["postData[queueStatus]"];

                        if (string.IsNullOrEmpty(queueId) || string.IsNullOrEmpty(queueStatus))
                        {
                            break;
                        }

                        var qId = Convert.ToInt64(queueId);
                        var qStatus = Convert.ToBoolean(queueStatus);

                        queueProvider = queueProvider ?? new ProdQueueDao();
                        var qUpdateStatus = queueProvider.UpdateQueuePause(qId, qStatus);

                        context.Response.Write(qUpdateStatus);
                        context.Response.End();
                        break;

                    case "GetTransectionByOrderNoAndMat":
                        string orderNo = post["postData[orderNo]"];
                        string matNo = post["postData[matNo]"];
                        transectionDao = transectionDao ?? new TransactionDao();
                        var transection = transectionDao.GetTransectionByOrderNoAndMatNo(orderNo, matNo);
                        string transectionSerialized = JsonConvert.SerializeObject(transection);
                        context.Response.Write(transectionSerialized);
                        context.Response.End();
                        break;
                    #endregion

                    #region User Fucntion

                    case "getAllRole":

                        roleProvider = roleProvider ?? new RoleDao();
                        var allRoles = roleProvider.GetAllRole();
                        string rolesSerialized = serializer.Serialize(allRoles);
                        context.Response.Write(rolesSerialized);
                        context.Response.End();

                        break;

                    case "getAllUser":

                        userProvider = userProvider ?? new UserDao();
                        var users = userProvider.GetAllUser();
                        string usersSerialized = JsonConvert.SerializeObject(users);
                        context.Response.Write(usersSerialized);
                        context.Response.End();

                        break;

                    case "login":

                        string username = post["username"];
                        string password = post["password"];
                        userProvider = userProvider ?? new UserDao();
                        var usersLogin = userProvider.Login(username, password);
                        string userLoggedSerialized = serializer.Serialize(usersLogin);
                        context.Response.Write(userLoggedSerialized);
                        context.Response.End();

                        break;

                    #endregion

                }
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}